<script setup>
import { computed, reactive, h,ref, watch } from 'vue'
import { Handle, Position, useVueFlow ,useNodesData} from '@vue-flow/core'
import { VMarkdownView } from 'vue3-markdown'
import Markdown from 'vue3-markdown-it';
import 'vue3-markdown/dist/style.css'
import BaseNode from './BaseNode.vue'
import AI from './ai.js'
import { NodeHandler } from './node.js'
// const TEST_SERVER = import.meta.env.VITE_SERVER
const props = defineProps(['id', 'data', 'sourceData', 'toggle'])
const loading= ref(false);
props.data.sourceData = null;
const { updateNodeData, getConnectedEdges, onConnect, onNodeClick, nodes, onNodesChange } = useVueFlow()
// const nodes = getNodes();

const target = ref("");
const example = ref("");
const aiResults = ref([])
const showAiRes = ref(false)
// const formatPoint =()=>{
//   let result = ""
//   for(let i = 0; i < items.value.length; i++){
//     result += `${i}. ${items.value[i]}\n`
//   }
//   return result
// }
const marktext = ref(''); 
const getNewMarkdown = () => {
  let points = ""
  if (aiArg.value.target != ""){
    points += `# ${aiArg.value.target}\n\n`
  }
  for(let i = 0; i < aiArg.value.points.length; i++){
    points += ` ${i+1}. ${aiArg.value.points[i]}\n`
  }
  if (aiArg.value.example != ""){
    points += `# 示例代码\n\n${aiArg.value.example}`
  }
  return points
}
const dataName = ref("")
const sourceId = ref("")
const types = ref([
  { label: 'Agent', value: 'Agent' },
  { label: 'JsonAgent', value: 'JsonAgent' },
  { label: 'ExcelDataAgent', value: 'ExcelDataAgent' },
  { label: 'MapReduceAgent', value: 'MapReduceAgent' },
  
])

const aiArg = ref({
  name: "",
  type: "Agent",
  target: "",
  points: [],
  example: "",
  useJson: false,
  points: [],
  batch_size: 10,
  data: [],
  threads: 1,
  use_json: false,
  model:"hammer2.1-1.5b",
  model_api:"http://xxx.xxx.xxx.xx/v1/chat/completions",
})





const markdown = ref("")

const saveAgent = () => {
  if (aiArg.value.target.trim() == ""){
    alert("至少输入使用的目的，简短描述即可")
    return
  }
  let handler = new NodeHandler(aiArg.value.name, aiArg.value.type)
  // handler.server = TEST_SERVER;
  handler.update(aiArg.value)
  handler.save((res) => {
    
  })
}

const delAgent = ()=>{
  if (aiArg.value.name.trim() == ""){
    alert("必须不为空")
    return
  }
  let handler = new NodeHandler(aiArg.value.name, aiArg.value.type)
  // handler.server = TEST_SERVER;
  handler.del((res) => {
    post_list_agent()
  })
}

const post_get_preview = () =>{
  console.log("post_get_preview")
  let handler = new NodeHandler(aiArg.value.name, aiArg.value.type)
  // handler.server = TEST_SERVER;
  handler.update(aiArg.value)
  handler.ai_config_preview((data)=>{
    if (Array.isArray(data.data)){
      markdown.value = data.data[0]
    }
    
  })
}


const active = ref(false)
const list_agent = ref([])
const use_agent_name = ref(aiArg.value.name);
const post_list_agent = () =>{
  NodeHandler.List((list)=>{
    list_agent.value = list.filter(v=> v.type.match(/Agent/g))
  })
}


const change_agent = () =>{
  setTimeout(()=>{
    let name = use_agent_name.value;
    console.log("change_agent:", name)
    let handler = new NodeHandler(name)
    // handler.server = TEST_SERVER;
    handler.load((data) => {
      let d = data;
      console.log("some reply:",d,)
      aiArg.value = d;
    })
  },300)
}

watch(use_agent_name, (newVal, oldVal) => {
  change_agent()
})



watch(aiArg, (newVal, oldVal) => {
  console.log('aiArg changed:', newVal)
  post_get_preview()
})


setTimeout(()=>{
  post_list_agent()

}, 200)

setTimeout(()=>{
  if (use_agent_name.value== "" && list_agent.value.length > 0){
    use_agent_name.value = list_agent.value[0].value
  }
},1000)


setInterval(post_list_agent, 30000)
const tmpUsename = ref("");
const sure_name = () =>{
  aiArg.value.name = tmpUsename.value;
}

const llm_msg = (prmpt, on_end) =>{
  let ai = new AI(aiArg.value.model_api, aiArg.value.model);
  ai.use_default_params();
  console.log("ai result:",aiResults.value);
  aiResults.value.push("");
  let ix = aiResults.value.length - 1;
  ai.stream(prmpt, (data) => {
    // console.log(data)
    loading.value = false;
    let msg = data.choices[0].delta.content;
    aiResults.value[ix] += msg;
  }, (finlly) => {
    on_end(finlly)
  })
}

const runLLm = () =>{
  
    showAiRes.value = true;
    loading.value = true;
    console.log("runLLm:", aiArg.value);
    fetch("/get_preview", {
        method: "POST",
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify(aiArg.value)
    }).then(res => res.json()).then((data) => {
        
        console.log("batchs:",data)
        let i = 0;
        let using = -1;
        let wait = setInterval(()=>{
          if (using < i){
            using += 1
            console.log("start :", using, " llm:",data.data[i])
            llm_msg(data.data[i], (finlly) => {
              i += 1
              if (i < data.data.length){
              }else{
                clearInterval(wait)
              }
            })
          }else{
            console.log("loading :", using, " ")
          }
        },1000)
        
    }).catch(e=>{
      console.log("exce:",e)
    })  

}
</script>

<template>
  
  <BaseNode :loading="loading" v-model:sourceData="aiArg.data" source extend>
    <template #extend>
      <n-list  style="padding:20px; " >
          <n-list-item v-if="aiResults.length > 0" >
            <n-button @click="aiResults = []"> 清理记录</n-button>
          </n-list-item>
          <n-list-item v-for="(aiRes,ix) in aiResults" >
            <!-- <vue-markdown-it :source="aiRes" style="max-width: 502px; overflow-y: auto" /> -->
            
            <Markdown  mode="dark" style="border-radius: 8px;max-width:67%;
    border: 1px solid gray;
    margin: 0px;
    overflow: auto;"
                              :source="aiRes" ></Markdown>
          </n-list-item>
        </n-list>
    </template>
    <n-card  style="text-align: start; padding: 4px;" >
      <n-space vertical>
        <n-h3 v-if="aiArg.name != '' ">{{ aiArg.name }}</n-h3>
        <n-tag size="tiny" type="success"  v-if="aiArg.model != ''" >{{ aiArg.model }}</n-tag>
        <n-tag  size="tiny" type="info" v-if="dataName != ''" >{{ dataName }}</n-tag>
        
      </n-space>
      <n-space vertical>
        <!-- <n-input v-if="aiArg.name == '' " v-model:value="tmpUsename" @keyup.enter="sure_name" placeholder="保存名字"></n-input> -->
        <n-select v-model:value="use_agent_name"  :options="list_agent"></n-select>
        
      </n-space>
      
      
      <n-flex style="margin-top: 10px;">
        <n-button @click="active = true">更多设置</n-button>
        <n-button type="success" v-if="aiArg.data.length > 0 || dataName == 'Searched data'" @click="runLLm"> 运行</n-button>
        <n-button type="success" v-if="aiRes != ''" @click="showAiRes = true"> 查看结果</n-button>
      </n-flex>
      
      
    </n-card>
    <n-drawer v-model:show="active" :width="502" :placement="placement">
      <n-drawer-content title="配置">
        <n-list>
          <n-list-item>
            加载已有Agent：<n-select v-model:value="use_agent_name"  :options="list_agent"></n-select>
          </n-list-item>
          <n-list-item>
            <n-space>
              <n-input v-model:value="aiArg.name" placeholder="保存名字"></n-input>
              <n-button @click="saveAgent">保存</n-button>
              <n-button @click="delAgent" type="warning" >删除</n-button>
            </n-space>
          </n-list-item>
          <n-list-item>
            <n-space vertical >
            
            <n-flex justify="space-between">
              是否使用JSON
              <n-switch v-model:value="aiArg.useJson">
                <template #checked>
                JSON
              </template>
              <template #unchecked>
                Text
              </template>
            </n-switch>
            </n-flex>

            
          
            <n-input v-model:value="aiArg.target" placeholder="任务目标" ></n-input>
          
          
            <n-dynamic-input
              v-model:value="aiArg.points"
              placeholder="具体要求"
              :min="1"
            />
          </n-space>
          </n-list-item>
          
          <n-list-item>
            <n-space vertical >
            单次处理多少个数据
            <n-input v-model:value="aiArg.batch_size" type="number"  :min="10" :max="100" ></n-input>
            并发数
            <n-input v-model:value="aiArg.threads" type="number" :max="5" ></n-input>
            </n-space>
          </n-list-item>
          <n-list-item>
            <n-input type="textarea" rows="7"  v-model:value="aiArg.example"  placeholder="输出示例（默认为空）" />
          </n-list-item>
          
          <n-list-item>
            <n-h2>Model 参数</n-h2>
          </n-list-item>
          <n-list-item>
            <n-space vertical>
              <n-input v-model:value="aiArg.model" placeholder="模型名字"></n-input>
              <n-input v-model:value="aiArg.model_api" placeholder="模型api"></n-input>
            </n-space>
          </n-list-item>
          <n-list-item>
                <div style="overflow: auto">
                  <VMarkdownView mode="dark" style="border-radius: 8px;
                              border: 1px solid gray;
                              margin: 0px;
                              padding: 13px;
                              overflow: auto;"
                                  :content="markdown" ></VMarkdownView>
                </div>  
          </n-list-item>
        </n-list>
      </n-drawer-content>
    </n-drawer>
    
  </BaseNode>
</template>

<style >
.n-card > .n-card__content:first-child, .n-card > .n-card__footer:first-child{
  padding: 0px;
}
</style>
